const { Op } = require("sequelize");

const brannerModel = appRequire('models/branner');

// 导出对象，供其它模块调用
module.exports = {
    list,
    save,
    destroy,
};

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {}
    if (postData.time) {
        let times = postData.time.split("-")
        let maxDay = new Date(times[0], times[1], 0).getDate()
        let startTime = postData.time + "-" + "01 00:00:00"
        let endTime = times[0] + "-" + times[1] + "-" + maxDay + " 23:59:59"
        params.time = {
            [Op.gte]: startTime,
            [Op.lte]: endTime
        }
    }

    let orders = [['createdAt', 'DESC']]
    let course = await brannerModel.todayBranner.findAndCountAll({
        where: params,
        order: orders,
        include: ['artPPT'],
    })
    course = Common.clone(course)
    let courseList = []
    for(let item of course.rows){
        if(item.artPPT && item.artPPT.title){
            item.artPPTName = item.artPPT.title
            delete item.artPPT

            courseList.push(item)
        }
    }

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

async function save(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['title'], request);
    if (checkResult == false) return;

    let params = {
        title: postData.title,
        time: postData.time,
    }
    if (postData.artpptId) params.artpptId = postData.artpptId
    if (postData.image) params.image = postData.image
    if (postData.objectId) {
        let result = await brannerModel.todayBranner.update(params, {
            where: {
                objectId: postData.objectId
            }
        })
        returnData.data = result
    } else {
        params.objectId = sid.uuid()
        let result = await brannerModel.todayBranner.create(params)
        returnData.data = result
    }

    request.json(returnData)
}

async function destroy(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let result = await brannerModel.todayBranner.destroy({
        where: {
            objectId: postData.objectId
        }
    })
    returnData.data = result
    request.json(returnData)
}